{% extends 'base.html' %}
{% load static %}

{% block title %}数据统计{% endblock %}

{% block content %}
<div class="row">
    <!-- 侧边栏（保持不变） -->
    <div class="col-md-3 col-lg-2 sidebar p-3">
        <div class="list-group">
            <a href="{% url 'dashboard' %}" class="list-group-item list-group-item-action" data-target="content-dashboard">仪表盘</a>
            <a href="{% url 'user_manage' %}" class="list-group-item list-group-item-action">用户管理</a>
            <a href="{% url 'content_manage' %}" class="list-group-item list-group-item-action">内容管理</a>
            <a href="{% url 'system_config' %}" class="list-group-item list-group-item-action">系统配置</a>
            <a href="{% url 'data_statistics' %}" class="list-group-item list-group-item-action active">数据统计</a>
            <a href="{% url 'log_manage' %}" class="list-group-item list-group-item-action">日志管理</a>
            <a href="{% url 'message_center' %}" class="list-group-item list-group-item-action">消息中心</a>
            <a href="{% url 'help_document' %}" class="list-group-item list-group-item-action">帮助文档</a>
        </div>
    </div>

    <!-- 内容区域 -->
    <div class="col-md-9 col-lg-10 p-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h3 class="text-xl font-bold text-gray-800">数据统计中心</h3>
            <div class="flex space-x-2">
                <div class="relative">
                    <select id="time-filter" class="appearance-none bg-white border border-gray-300 rounded-lg pl-3 pr-10 py-2 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                        <option value="7days">近7天</option>
                        <option value="30days" selected>近30天</option>
                        <option value="90days">近90天</option>
                        <option value="custom">自定义...</option>
                    </select>
                    <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700">
                        <i class="fa fa-chevron-down text-xs"></i>
                    </div>
                </div>
                <button id="export-data" class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg transition-all flex items-center">
                    <i class="fa fa-download mr-2"></i> 导出数据
                </button>
            </div>
        </div>

        <!-- 关键指标卡片 -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
            <div class="bg-white rounded-lg shadow-sm p-5 border-l-4 border-primary">
                <div class="flex justify-between items-start">
                    <div>
                        <p class="text-sm font-medium text-gray-500">总用户数</p>
                        <h3 class="text-2xl font-bold text-gray-900 mt-1" id="total-users">12,543</h3>
                        <p class="text-sm mt-2 text-green-500 flex items-center">
                            <i class="fa fa-arrow-up mr-1"></i> 12.5% <span class="text-gray-500 ml-1">较上月</span>
                        </p>
                    </div>
                    <div class="bg-primary/10 p-3 rounded-lg">
                        <i class="fa fa-users text-primary text-xl"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow-sm p-5 border-l-4 border-indigo-500">
                <div class="flex justify-between items-start">
                    <div>
                        <p class="text-sm font-medium text-gray-500">总内容数</p>
                        <h3 class="text-2xl font-bold text-gray-900 mt-1" id="total-content">3,245</h3>
                        <p class="text-sm mt-2 text-green-500 flex items-center">
                            <i class="fa fa-arrow-up mr-1"></i> 8.2% <span class="text-gray-500 ml-1">较上月</span>
                        </p>
                    </div>
                    <div class="bg-indigo-500/10 p-3 rounded-lg">
                        <i class="fa fa-file-text-o text-indigo-500 text-xl"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow-sm p-5 border-l-4 border-teal-500">
                <div class="flex justify-between items-start">
                    <div>
                        <p class="text-sm font-medium text-gray-500">总访问量</p>
                        <h3 class="text-2xl font-bold text-gray-900 mt-1" id="total-visits">256,789</h3>
                        <p class="text-sm mt-2 text-green-500 flex items-center">
                            <i class="fa fa-arrow-up mr-1"></i> 18.7% <span class="text-gray-500 ml-1">较上月</span>
                        </p>
                    </div>
                    <div class="bg-teal-500/10 p-3 rounded-lg">
                        <i class="fa fa-eye text-teal-500 text-xl"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow-sm p-5 border-l-4 border-amber-500">
                <div class="flex justify-between items-start">
                    <div>
                        <p class="text-sm font-medium text-gray-500">互动总量</p>
                        <h3 class="text-2xl font-bold text-gray-900 mt-1" id="total-interactions">45,217</h3>
                        <p class="text-sm mt-2 text-red-500 flex items-center">
                            <i class="fa fa-arrow-down mr-1"></i> 3.1% <span class="text-gray-500 ml-1">较上月</span>
                        </p>
                    </div>
                    <div class="bg-amber-500/10 p-3 rounded-lg">
                        <i class="fa fa-comments text-amber-500 text-xl"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- 图表区域 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
            <!-- 用户增长趋势 -->
            <div class="bg-white rounded-lg shadow-sm p-5">
                <div class="flex justify-between items-center mb-4">
                    <h5 class="text-lg font-semibold text-gray-800">用户增长趋势</h5>
                    <div class="flex space-x-2">
                        <button class="text-sm px-3 py-1 bg-primary/10 text-primary rounded-full" data-chart-type="line">折线图</button>
                        <button class="text-sm px-3 py-1 bg-gray-100 text-gray-600 rounded-full" data-chart-type="bar">柱状图</button>
                    </div>
                </div>
                <div class="h-80">
                    <canvas id="userChart"></canvas>
                </div>
            </div>

            <!-- 内容发布统计 -->
            <div class="bg-white rounded-lg shadow-sm p-5">
                <div class="flex justify-between items-center mb-4">
                    <h5 class="text-lg font-semibold text-gray-800">内容发布统计</h5>
                    <div class="flex space-x-2">
                        <button class="text-sm px-3 py-1 bg-primary/10 text-primary rounded-full" data-chart-type="line">折线图</button>
                        <button class="text-sm px-3 py-1 bg-gray-100 text-gray-600 rounded-full" data-chart-type="bar">柱状图</button>
                    </div>
                </div>
                <div class="h-80">
                    <canvas id="contentChart"></canvas>
                </div>
            </div>

            <!-- 内容类型分布 -->
            <div class="bg-white rounded-lg shadow-sm p-5">
                <div class="flex justify-between items-center mb-4">
                    <h5 class="text-lg font-semibold text-gray-800">内容类型分布</h5>
                    <div class="flex space-x-2">
                        <button class="text-sm px-3 py-1 bg-primary/10 text-primary rounded-full" data-chart-type="pie">饼图</button>
                        <button class="text-sm px-3 py-1 bg-gray-100 text-gray-600 rounded-full" data-chart-type="bar">柱状图</button>
                    </div>
                </div>
                <div class="h-80">
                    <canvas id="contentTypeChart"></canvas>
                </div>
            </div>

            <!-- 用户活跃度分析 -->
            <div class="bg-white rounded-lg shadow-sm p-5">
                <div class="flex justify-between items-center mb-4">
                    <h5 class="text-lg font-semibold text-gray-800">用户活跃度分析</h5>
                    <div class="flex space-x-2">
                        <button class="text-sm px-3 py-1 bg-primary/10 text-primary rounded-full" data-chart-type="bar">柱状图</button>
                        <button class="text-sm px-3 py-1 bg-gray-100 text-gray-600 rounded-full" data-chart-type="line">折线图</button>
                    </div>
                </div>
                <div class="h-80">
                    <canvas id="userActivityChart"></canvas>
                </div>
            </div>
        </div>

        <!-- 详细数据表格 -->
        <div class="bg-white rounded-lg shadow-sm p-5 mb-6">
            <div class="flex justify-between items-center mb-4">
                <h5 class="text-lg font-semibold text-gray-800">详细数据</h5>
                <div class="flex space-x-2">
                    <div class="relative">
                        <select id="data-table-filter" class="appearance-none bg-white border border-gray-300 rounded-lg pl-3 pr-10 py-2 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                            <option value="daily">每日数据</option>
                            <option value="weekly">每周数据</option>
                            <option value="monthly">每月数据</option>
                        </select>
                        <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700">
                            <i class="fa fa-chevron-down text-xs"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">日期</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">新增用户</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">发布内容</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">访问量</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">互动量</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">转化率</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200" id="detail-data-table">
                        <!-- 表格数据由JavaScript动态生成 -->
                    </tbody>
                </table>
            </div>
            <div class="mt-4 flex justify-between items-center">
                <div class="text-sm text-gray-500">
                    显示 1-10 条，共 30 条
                </div>
                <div class="flex space-x-1">
                    <button class="px-3 py-1 rounded border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">上一页</button>
                    <button class="px-3 py-1 rounded border border-primary bg-primary text-sm font-medium text-white">1</button>
                    <button class="px-3 py-1 rounded border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">2</button>
                    <button class="px-3 py-1 rounded border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">3</button>
                    <button class="px-3 py-1 rounded border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">下一页</button>
                </div>
            </div>
        </div>
    </div>
</div>
{% block extra_js %}
<script>
    // 侧边栏交互逻辑
    document.querySelectorAll('.list-group-item').forEach(item => {
        item.addEventListener('click', function(e) {
            document.querySelector('.list-group-item.active').classList.remove('active');
            this.classList.add('active');
        });
    });
</script>
{% endblock %}


<script src="{% static 'js/chart.umd.min.js' %}"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 生成日期数组（近30天）
    function generateDateLabels(days = 30) {
        const labels = [];
        for (let i = days - 1; i >= 0; i--) {
            const date = new Date();
            date.setDate(date.getDate() - i);
            labels.push(date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' }));
        }
        return labels;
    }

    // 生成随机数据
    function generateRandomData(length, min, max) {
        return Array.from({ length }, () => Math.floor(Math.random() * (max - min + 1)) + min);
    }

    // 格式化数字为千分位
    function formatNumber(num) {
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    // 初始化图表
    const dateLabels = generateDateLabels(30);
    const userData = generateRandomData(30, 10, 200);
    const contentData = generateRandomData(30, 5, 80);
    const visitData = generateRandomData(30, 1000, 5000);
    const interactionData = generateRandomData(30, 200, 1000);

    // 用户增长趋势图表
    const userChartCtx = document.getElementById('userChart').getContext('2d');
    const userChart = new Chart(userChartCtx, {
        type: 'line',
        data: {
            labels: dateLabels,
            datasets: [{
                label: '新增用户',
                data: userData,
                borderColor: '#3b82f6',
                backgroundColor: 'rgba(59, 130, 246, 0.1)',
                tension: 0.3,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    mode: 'index',
                    intersect: false,
                    callbacks: {
                        label: function(context) {
                            return `新增用户: ${formatNumber(context.raw)}`;
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        drawBorder: false
                    }
                },
                x: {
                    grid: {
                        display: false
                    }
                }
            },
            interaction: {
                mode: 'nearest',
                axis: 'x',
                intersect: false
            },
            animations: {
                tension: {
                    duration: 1000,
                    easing: 'linear'
                }
            }
        }
    });

    // 内容发布统计图表
    const contentChartCtx = document.getElementById('contentChart').getContext('2d');
    const contentChart = new Chart(contentChartCtx, {
        type: 'line',
        data: {
            labels: dateLabels,
            datasets: [{
                label: '发布内容',
                data: contentData,
                borderColor: '#8b5cf6',
                backgroundColor: 'rgba(139, 92, 246, 0.1)',
                tension: 0.3,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    mode: 'index',
                    intersect: false,
                    callbacks: {
                        label: function(context) {
                            return `发布内容: ${formatNumber(context.raw)}`;
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        drawBorder: false
                    }
                },
                x: {
                    grid: {
                        display: false
                    }
                }
            },
            interaction: {
                mode: 'nearest',
                axis: 'x',
                intersect: false
            },
            animations: {
                tension: {
                    duration: 1000,
                    easing: 'linear'
                }
            }
        }
    });

    // 内容类型分布图表
    const contentTypeChartCtx = document.getElementById('contentTypeChart').getContext('2d');
    const contentTypeChart = new Chart(contentTypeChartCtx, {
        type: 'pie',
        data: {
            labels: ['文章', '图片', '视频', '音频', '其他'],
            datasets: [{
                data: [45, 25, 15, 10, 5],
                backgroundColor: [
                    '#3b82f6',
                    '#8b5cf6',
                    '#10b981',
                    '#f59e0b',
                    '#6b7280'
                ],
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'right'
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return `${context.label}: ${context.raw}%`;
                        }
                    }
                }
            },
            animations: {
                animateRotate: true,
                animateScale: true
            }
        }
    });

    // 用户活跃度分析图表
    const userActivityChartCtx = document.getElementById('userActivityChart').getContext('2d');
    const userActivityChart = new Chart(userActivityChartCtx, {
        type: 'bar',
        data: {
            labels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
            datasets: [{
                label: '活跃用户',
                data: [1200, 1500, 1300, 1400, 1600, 2200, 2000],
                backgroundColor: [
                    'rgba(59, 130, 246, 0.7)',
                    'rgba(59, 130, 246, 0.7)',
                    'rgba(59, 130, 246, 0.7)',
                    'rgba(59, 130, 246, 0.7)',
                    'rgba(59, 130, 246, 0.7)',
                    'rgba(59, 130, 246, 0.9)',
                    'rgba(59, 130, 246, 0.9)'
                ],
                borderRadius: 4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return `活跃用户: ${formatNumber(context.raw)}`;
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        drawBorder: false
                    }
                },
                x: {
                    grid: {
                        display: false
                    }
                }
            }
        }
    });

    // 填充详细数据表格
    const tableBody = document.getElementById('detail-data-table');
    for (let i = 0; i < 10; i++) {
        const row = document.createElement('tr');
        row.className = i % 2 === 0 ? 'bg-white' : 'bg-gray-50';

        const date = new Date();
        date.setDate(date.getDate() - i);
        const formattedDate = date.toLocaleDateString('zh-CN');

        row.innerHTML = `
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${formattedDate}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${formatNumber(userData[userData.length - 1 - i])}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${formatNumber(contentData[contentData.length - 1 - i])}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${formatNumber(visitData[visitData.length - 1 - i])}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${formatNumber(interactionData[interactionData.length - 1 - i])}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm">
                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">
                    ${(Math.random() * 10 + 2).toFixed(1)}%
                </span>
            </td>
        `;

        tableBody.appendChild(row);
    }

    // 图表类型切换
    const chartButtons = document.querySelectorAll('[data-chart-type]');
    chartButtons.forEach(button => {
        button.addEventListener('click', function() {
            const chartType = this.getAttribute('data-chart-type');
            const parent = this.closest('.bg-white');
            const chartId = parent.querySelector('canvas').id;
            const chart = Chart.getChart(chartId);

            // 更新按钮样式
            this.parentElement.querySelectorAll('button').forEach(btn => {
                btn.className = 'text-sm px-3 py-1 bg-gray-100 text-gray-600 rounded-full';
            });
            this.className = 'text-sm px-3 py-1 bg-primary/10 text-primary rounded-full';

            // 更新图表类型
            if (chart) {
                chart.config.type = chartType;
                chart.update();
            }
        });
    });

    // 时间筛选器
    const timeFilter = document.getElementById('time-filter');
    timeFilter.addEventListener('change', function() {
        if (this.value === 'custom') {
            alert('自定义时间范围功能将在未来版本中实现');
            this.value = '30days';
            return;
        }

        // 根据选择的时间范围更新图表数据
        let days;
        switch(this.value) {
            case '7days':
                days = 7;
                break;
            case '30days':
                days = 30;
                break;
            case '90days':
                days = 90;
                break;
            default:
                days = 30;
        }

        const newDateLabels = generateDateLabels(days);
        const newUserData = generateRandomData(days, 10, 200);
        const newContentData = generateRandomData(days, 5, 80);

        // 更新图表数据
        userChart.data.labels = newDateLabels;
        userChart.data.datasets[0].data = newUserData;
        userChart.update();

        contentChart.data.labels = newDateLabels;
        contentChart.data.datasets[0].data = newContentData;
        contentChart.update();

        // 更新表格数据
        tableBody.innerHTML = '';
        for (let i = 0; i < Math.min(10, days); i++) {
            const row = document.createElement('tr');
            row.className = i % 2 === 0 ? 'bg-white' : 'bg-gray-50';

            const date = new Date();
            date.setDate(date.getDate() - i);
            const formattedDate = date.toLocaleDateString('zh-CN');

            row.innerHTML = `
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${formattedDate}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${formatNumber(newUserData[newUserData.length - 1 - i])}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${formatNumber(newContentData[newContentData.length - 1 - i])}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${formatNumber(generateRandomData(1, 1000, 5000)[0])}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${formatNumber(generateRandomData(1, 200, 1000)[0])}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm">
                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">
                        ${(Math.random() * 10 + 2).toFixed(1)}%
                    </span>
                </td>
            `;

            tableBody.appendChild(row);
        }
    });

    // 导出数据按钮
    const exportButton = document.getElementById('export-data');
    exportButton.addEventListener('click', function() {
        alert('数据导出功能将在未来版本中实现');
    });

    // 表格筛选器
    const tableFilter = document.getElementById('data-table-filter');
    tableFilter.addEventListener('change', function() {
        alert(`已切换至${this.options[this.selectedIndex].text}数据`);
    });
});
</script>
{% endblock %}